var express = require('express');
var router = express.Router();

/* GET home page. */
router.get('/', function (req, res, next) {
    res.render('index', { title: 'Express' });
});




const { api_url } = require("../config/config.js")
const query = require("../tools/db.js")


// 1、轮播图------
router.get("/banners", async (req, res, next) => {

    // 查询数据库中的e_banners表
    // let sql=`select *  from e_banners where isshow=1`

    /* let sql=`select 
                    id,
                    concat("http://localhost:3000","/uploads", image_src),
                    title,
                    isshow  
            from e_banners 
            where isshow=1` */


    let sql = `select 
                    id,
                    concat("${api_url}","/uploads/", image_src) as image_src ,
                    title,
                    isshow  
            from e_banners 
            where isshow=1`
    let [err, results] = await query(sql)
    // console.log(err,results);
    // banners/tbanner1.png  拼接路径
    // http://localhost:3000/uploads/banners/tbanner1.png


    if (err) {
        next("轮播图请求失败")
        return
    }


    res.send({
        status: 200,//状态码
        msg: "轮播图请求成功",
        results
    })
})



// 2、同步课程、精品课程------
router.get("/courses" ,async (req,res,next)=>{

    // 希望请求时传递一个type参数 1同步 2精品
    let {type}=req.query
    if(type!=1&&type!=2){
        next("请传递正确的参数")
        return
    }

    // 请求数据库
    let sql=`select 
                    id,
                    cid,
                    title,
                    price,
                    concat("${api_url}","/uploads/","index/",image_src) as  image_src,
                    type,
                    type_name,
                    area_name,
                    subject_name
             from e_course 
             where type=${type} && (status=1 ||status=2)
             limit ${ type==1?"8":"6" }
             `

    let [err,results]=await query(sql)

    // res.send([err,results])


    // 错误拦截
    if(err){
        next( type==1?"同步"+"课程请求失败":"精品"+"课程请求失败" )
        return
    }


    // 发送正确结果
    res.send({
        status:200,
        msg:type==1?"同步"+"课程请求成功":"精品"+"课程请求成功",
        results
    })

})





module.exports = router;
